<?php
class User extends CActiveRecord
{
	/**
	 * The followings are the available columns in table '_user':
	 * @var integer $id
	 * @var string $username
	 * @var string $password
	 * @var string $salt
	 * @var string $email
	 * @var string $profile
	 */
	public $password2;
	public $oldpassword;
	public $verifyCode;
	public $checkDbPassword;
	public $copyaddress;
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{users}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(

			// array('email', 'email', 'allowEmpty' => false,'on'=>array('clientsearch')),
			//array('id,name,email','ext.atLeastValidator'),	
			array('id,name,email','ext.AtLeastValidator', 'on'=>array('clientsearch')),

			array('email','required','on'=>array('reset')),
			array('password, password2 ', 'required','on'=>array('reset')),
						
			array('type,password,password2,verifyCode', 'required','on'=>array('registration')),
			array('email,name,country_id,state_id,city_id,phone1', 'required','on'=>array('registration','personalinfo')),
			array('oldpassword,password,password2','required','on'=>array('changepass')),
			array('email', 'email','on'=>array('registration','reset')),
			array('email', 'unique','on'=>array('registration')),
			array('password, password2', 'length', 'max'=>8,'on'=>array('registration')),
			array('name', 'length', 'max'=>30,'on'=>array('registration','personalinfo')),
			array('password2', 'compare', 'compareAttribute'=>'password','on'=>array('registration','changepass')),
			array('name','match', 'pattern' => '/^[a-zA-Z]+( [a-zA-Z]+)*$/','on'=>array('registration','personalinfo'),'message' => 'No Special Charaters and Numbers are Allow in this Field'),
			array('phone1, phone2', 'length', 'min'=>8,'on'=>array('registration','personalinfo')),
			array('phone1, phone2', 'length', 'max'=>11,'on'=>array('registration','personalinfo')),
			array('phone1, phone2, fax', 'match', 'pattern'=>'/^([0-9]*|\d*\-\d*|\+\d*)$/','on'=>array('registration','personalinfo'),'message' => 'Invalid data Entered' ),
			array('fax', 'length', 'is'=>10,'on'=>array('registration','personalinfo')),
			array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd'),'on'=>'registration'),
			//array('username, password, salt, email', 'length', 'max'=>128),
			array('password2', 'compare', 'compareAttribute'=>'password','on'=>array('registration','reset')),
			array('profile', 'safe'),
			array('oldpassword', 'compare', 'compareAttribute'=>'checkDbPassword','on'=>array('changepass'),'message'=>'InValid Old Password'),
			array(
			  'password',
			  'compare',
			  //'compareAttribute'=>'checkDbPassword',
			  'compareAttribute'=>'oldpassword',
        	  //'compareValue'=>'min_year',
			  'operator'=>'!=', 
			  'allowEmpty'=>true , 
        	  'on'=>'changepass',
        	//'strict'=>true,
			  'message'=>"Choose a password you haven't previously used with this account.",
			), 
			
		);
	} ///^[A-Za-z]+$/u
	//"^[a-zA-Z0-9]+$"

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'posts' => array(self::HAS_MANY, 'Post', 'author_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Id',
			'username' => 'Email',
			'password' => 'Password',
			'password2' => 'Confirm Password',
			'oldpassword'=> 'Old Password',
			'salt' => 'Salt',
			'email' => 'Email',
			'profile' => 'Profile',
			'country_id'=> 'Country Name',
			'state_id'=> 'State Name',
			'city_id'=> 'City Name',
			'phone1'=> 'Phone no 1',
			'phone2'=> 'Phone no 2',
			'fax'=>'Fax no',
			'verifyCode'=>'Verification code',
		);
	}

	
	
	public function isActive($ids,$status='active')
	{
		$criteria=new CDbCriteria;
		$criteria->condition='status=:status';
		$criteria->params=array(':status'=>$status);
		$criteria->addInCondition('id',$ids);
		$objRows=$this->findAll($criteria);
	    foreach ($objRows as $objRow) {
			$row[]=$objRow->id;
		}
		if($row)
		{
			return $row;
		}
		else {
		return false;
		}
		
	}
	
	/**
	 * Finds users
	 * @param string type
	 * @param string status
	 * @return array 
	 */
	public function getUsers($type='client',$status='active')
	{
		$criteria=new CDbCriteria;
		$criteria->condition='type=:type AND status=:status';
		$criteria->params=array(':type'=>$type, ':status'=>$status);
		$objRows=$this->findAll($criteria);
		foreach ($objRows as $objRow) {
			$row[]=$objRow->id;
		}
		if($row)
		{
			return $row;
		}
		else {
		return false;
		}
	}
	
	/**
	 * Checks if the given password is correct.
	 * @param string the password to be validated
	 * @return boolean whether the password is valid
	 */
	public function validatePassword($password)
	{
		//echo '<br> in validatePassword function<br>';
		//echo 'Password : '.$password; echo '<br>';
		//echo 'dbpassword :'. $this->password;exit;
		return $this->hashPassword($password,$this->salt)===$this->password;
		//return $password == $this->password;
		
	}
	
	public static function getCriteria($type, $arrParams)
	{
		switch ($type)
		{
			case "COMPANY-SEARCH":
				if(is_array($arrParams))
                { 
                    $criteria=new CDbCriteria;
                    $criteria->compare('name',$arrParams['companyname'],false);
                    $criteria->compare('id',$arrParams['companyid'],false);
                    $criteria->compare('email',$arrParams['companyemail'],false);
                    $criteria->compare('type','company',false);
					//echo "<pre>";
  					//print_r($criteria); exit;
                    /*$result = ManageAuctionListing::model()->findAll($criteria);
                    echo "<br>Count is    ".count($result);
                    echo "<pre>";
                    print_r($result); exit;*/
                    return $criteria;
                }
                //echo "end";
            break;  
            
            case "CLIENT-SEARCH":
				//echo "start";
				if(is_array($arrParams))
				{
					$criteria=new CDbCriteria;
					$criteria->compare('id',$arrParams['objUser']['id'],true,'OR');
					$criteria->compare('name',$arrParams['objUser']['name'],true,'OR');
					$criteria->compare('email',$arrParams['objUser']['email'],true,'OR');
					$criteria->compare('type','client',false);
					$criteria->addNotInCondition('id',$arrParams['noInClient']);
					//print_r($criteria); exit;
					return $criteria;
				}
				//echo "end";
			break;	 
	            case 'COMPANY-LIST':
					$criteria=new CDbCriteria;
					$criteria->addInCondition ('id',$arrParams);
					//$arrCompanyList = $this->findAll($criteria);
	                //echo print_r($arrCompanyList);exit;
				return $criteria;
			break; 

			case "CLIENT-LIST-BY-COMPANY-ID":
					$criteria=new CDbCriteria;
		            //$criteria->compare('id',$arrParams['company_id']);
					$criteria->compare('type','client');
					//$criteria->compare('status','active',false,'OR');
					$criteria->addInCondition('id',$arrParams['client_ids']);
					$criteria->order = 'created DESC' ;
					//print_r($criteria); exit;	
				return $criteria;
			 break;
                  
		}		
	} 

	/**
	 * Generates the password hash.
	 * @param string password
	 * @param string salt
	 * @return string hash
	 */
	public function hashPassword($password,$salt)
	{
		//echo '<br> in hashPassword function<br>';
		//echo 'Password : '.$password; echo '<br>';
		//echo 'salt  :'. $salt;echo '<br>';
		//echo 'mdpassword  :'. md5($salt.$password);
		return md5($password.$salt);
		//return md5($password);
	}

	/**
	 * Generates a salt that can be used to generate a password hash.
	 * @return string the salt
	 */
	public function generatesalt()
	{
		return microtime();
	}

	public function beforeSave() 
	{
		//Using MD5 to hash password and salt
     	if($this->isNewRecord)
     	{
        	$this->password=md5($this->password . $this->salt);
     	}
     	return true;
 	}
 	
	
	 
	public static function getList($type,$arrParams = array())
	{
		switch ($type)
		{
			// not using following case of COUNTRY-LIST
			case 'COUNTRY-LIST':
				$arrCountryList = Country::model()->findAll();
				foreach ($arrCountryList as $CountryList)
				{
					$AllCountryList[$CountryList->id] = $CountryList->city_name;
				}
			return $AllCountryList;
			break;
			
			case 'COMPANY-LIST':
				$criteria=new CDbCriteria;
				$criteria->addInCondition('id',$arrParams);
				$objRows=User::model()->findAll($criteria);	
		   		 foreach ($objRows as $objRow)
				{
					$arrCompanyList[$objRow->id] = $objRow->id.' # '.$objRow->name;
				}
				return $arrCompanyList;
			break;	
			
		}
	}
	
	public function getModel($type, $arrParams)
	{
		switch($type)
		{
			case "BY-USER-ID":
				$objUser = User::model()->findByPk((int)$arrParams['user_id']);
			return $objUser;
			 break;
			 
			 case "USER-EMAIL":
					$user=User::model()->find(array(
            							'condition'=>'email=:email',
	    								'params'=>array('email'=>$arrParams['email']),
        								));				
					return $user;
				break;
				case "USER-FORGOT_PASSWORD_IDENTIFIER":
					$user=User::model()->find(array(
            							'condition'=>'forgot_password_identifier=:forgot_password_identifier',
	    								'params'=>array('forgot_password_identifier'=>$arrParams['forgot_password_identifier']),
        								));				
					return $user;
				break;
	
		}
	}
	
}